package com.djx.goods.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.djx.common.domain.Type;
import com.djx.goods.mapper.TypesMapper;
import com.djx.goods.service.TypeService;
import org.redisson.Redisson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.convert.TypeMapper;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class TypeServiceImpl implements TypeService {
    @Resource
    private TypesMapper typesMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<Type> getList() {
        ListOperations<String, String> forList = redisTemplate.opsForList();
        String s = forList.leftPop("type");
        List<Type> typeList = JSONObject.parseObject(s, List.class);
        if (typeList!=null){
            return typeList;
        }
        List<Type> list=typesMapper.getList();
        getPids(list);
        return list;
    }

    private void getPids(List<Type> list) {
        for (Type type : list) {
                List<Type> countPids=typesMapper.getChildren(type.getId());
                if (countPids.size()==0){
                    type.setChildren(null);
                }else {
                    for (Type countPid : countPids) {
                        if (countPid!=null){
                            getPids(countPids);
                        }
                    }
                    type.setChildren(countPids);
                }
        }
    }
}
